package com.ly.mp.dal.comm.jdbc;

import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;

public class MpJdbcTemplate extends JdbcTemplate {
    private static final Logger log = LoggerFactory.getLogger(MpJdbcTemplate.class);
    private String transactionPolicy;

    public MpJdbcTemplate() {
    }

    public MpJdbcTemplate(DataSource dataSource) {
        this.setDataSource(dataSource);
        this.afterPropertiesSet();
    }

    public MpJdbcTemplate(DataSource dataSource, String transactionPolicy) {
        this.transactionPolicy = transactionPolicy;
        this.setDataSource(dataSource);
        this.afterPropertiesSet();
    }

    public MpJdbcTemplate(DataSource dataSource, boolean lazyInit) {
        this.setDataSource(dataSource);
        this.setLazyInit(lazyInit);
        this.afterPropertiesSet();
    }

    // 重写了获取dataSource的方法, 所以可以控制 来动态切换数据源
    @Override
    public DataSource getDataSource() {
        if ("jta".equals(this.transactionPolicy)) {
            DataSource axDs = ((DynamicDataSource) super.getDataSource()).getTargetDataSource();
            log.info("分布式事务获取当前数据源key:{}", ReadWriteDataSourceDecision.getDsKey());
            return axDs;
        } else {
            log.info("不是分布式事务模式,获取当前数据源key:{}", ReadWriteDataSourceDecision.getDsKey());
            DynamicDataSource dataSource = (DynamicDataSource) super.getDataSource();
            return dataSource.getAcuallyDataSource();
        }
    }
}